<?php
namespace Home\Controller;

use Think\Controller;
use Common\Util\LanzSMSDirectSendSMS;

/**
 * 支付
 * @author Administrator
 *
 */
class PayController extends Controller {
	
	public function _initialize() {
		//引入WxPayPubHelper
		vendor('WxPayPubHelper.WxPayPubHelper');
	}
	
	public function index() {
		if (!IS_POST) {
			$this->assign('content', '错误提交');
			$this->display('Public/nodata');
			exit;
		}
		
		$orderId = I('post.order_id');
		$userId = getSessionUserId();
		if (!$orderId) {
			$id = I ('post.service_id');
			$beautyId = I ('post.beauty_id');
			$beauticianId = I ('post.beautician_id');
				
			$Model = D('ServiceItem');
			$item = $Model->getServiceInfo($id);
				
			$OrderModel = D('Order');
				
			$beauticianInfo = D('Beautician')->getBeauticianInfo($beauticianId);
			$BeautiParlorInfo = D('BeautyParlor')->getBeautyInfo($beautyId);
				
			$couponId = I('post.coupon_id');
			if ($couponId) {
				$UserCouponModel = D('UserCoupon');
				$userCouponInfo = $UserCouponModel->where(array('id' => $couponId))->find();
				if (!$userCouponInfo || $userCouponInfo ['status'] != 1 || $userCouponInfo ['user_id'] != $userId ) {
// 					$this->ajaxReturn(array('status' => 0, 'message' => '卡券编号有误或已使用'));
					$this->assign('content', '卡券编号有误或已使用');
					$this->display('Public/nodata');
					exit;
				}
			}
			
			$orderDate = date("Y-m-d");
			$dayStart = strtotime ( $orderDate . ' 00:00:00' );
			$dayEnd = strtotime ( $orderDate . ' 23:59:59' );
			$orderDayStart = strtotime ( $orderDate . ' 08:00:00' );
			$orderDayEnd = strtotime ( $orderDate . ' 22:00:00' );
			
			$ScheduleModel = M('schedule');
			$setting = $ScheduleModel->where(array('uid' => $beauticianId))->order('CurrentDate DESC')->limit(1)->find();
			//检测设置的日程
// 			if ($setting) {
// 				$setting = unserialize($setting ['workTime']);
// 			} else {
// 				$this->assign('content', '您预约的时间段，该美容师繁忙，无法为您提供服务。请选择其它美容师');
// 				$this->display('Public/nodata');
// 				exit();
// 			}

			//下单日起的日程设置
			$setting = isset($setting [$dayStart])?$setting [$dayStart]:array();
			$canOrder = false;
			$orderTime = I('post.order_time');
			if (!$setting) {
				$canOrder = true;
// 				$this->assign('content', '您预约的时间段，该美容师繁忙，无法为您提供服务。请选择其它美容师');
// 				$this->display('Public/nodata');
// 				exit();
			} else {
				foreach ($setting as $key => $value) {
					$hour = ceil($item ['service_time']/60);
				
					if ($value ['start'] >= $orderTime &&
					$value ['end'] > (($hour + 1) * 60  + $orderTime)) {
						$canOrder = true;
					}
				}
			}
			
			//首先判断设置的日程里面的时间是否可预约
			if (!$canOrder) {
				$this->assign('content', '您预约的时间段，该美容师繁忙，无法为您提供服务。请选择其它美容师');
				$this->display('Public/nodata');
				exit();
			}
			
			$existOrder = $OrderModel->checkCanOrder($beauticianId, $orderTime, $orderDayStart, $orderTime + ($hour + 1) * 3600);
// 			dump($existOrder);die;
			if ($existOrder) {
				$this->assign('content', '您预约的时间段，该美容师繁忙，无法为您提供服务。请选择其它美容师');
				$this->display('Public/nodata');
				exit();
			}
			
			$order_number = $this->createOrder();
			
			$time = time();
			$data = array(
				'order_number' => $order_number,
				'service_id' => $id,
				'service_name' => $item ['service_name'],
				'service_time' => $item ['service_time'],
				'price' => $item ['price'],
				'beauty_id' => $beautyId,
				'beauty_name' => $BeautiParlorInfo ['name'],
				'beautician_id' => $beauticianId,
				'beautician_name' => $beauticianInfo ['name'],
				'service_address' => $BeautiParlorInfo ['address'],
				'pay_method_type' => I('post.pay_method_type'),
				'user_id' => $userId,
				'coupon_id' => $couponId,
				'order_time' => $orderTime,
				'expire_time' => $time + 10 * 60,
				'created' => $time,
			);
				
			$orderId = $OrderModel->createOrder($data);
			if (!$orderId) {
				$this->assign('content', '订单创建失败');
				$this->display('Public/nodata');
				exit;
// 				$this->ajaxReturn(array('status' => 0, 'message' => '订单创建失败'));
			}
		} else {
			
			$OrderModel = D('Order');
			$data = $OrderModel->where(array('id' => $orderId))->find();
			$OCouponId = $data ['coupon_id'];
			$postCouponId = I('post.coupon_id');
			
			if ($postCouponId) {
				$UserCouponModel = D('UserCoupon');
				$userCouponInfo = $UserCouponModel->where(array('id' => $postCouponId))->find();
				if (!$userCouponInfo || $userCouponInfo ['status'] != 1 || $userCouponInfo ['user_id'] != $userId ) {
// 					$this->ajaxReturn(array('status' => 0, 'message' => '卡券编号有误或已使用'));
					$this->assign('content', '卡券编号有误或已使用');
					$this->display('Public/nodata');
					exit;
				}
			}
			
			if ($couponId != $postCouponId) {
				$couponId = $postCouponId?$postCouponId:0;
				$OrderModel->where(array('id' => $orderId))->save(array('coupon_id' => $postCouponId));
				$OrderModel->clearCache($orderId);
			}
			
			$beauticianInfo = D('Beautician')->getBeauticianInfo($data ['beautician_id']);
			$BeautiParlorInfo = D('BeautyParlor')->getBeautyInfo($data ['beauty_id']);
		}
		
		
		$dec = 0;
		if ($couponId && $userCouponInfo) {
			$dec = $userCouponInfo ['c_type'] != 2?$userCouponInfo ['money_reduce']:$userCouponInfo ['money_amount'];
			$this->assign('coupon', $userCouponInfo);
		}
		
		//使用jsapi接口
		$jsApi = new \JsApi_pub();
		 
		//=========步骤1：网页授权获取用户openid============
		$user = getSessionUser();
		$openid = $user ['open_id'];
		
		//=========步骤2：使用统一支付接口，获取prepay_id============
		//使用统一支付接口
		$unifiedOrder = new \UnifiedOrder_pub();
		
		$pay = $data ['price'] - $dec;
		 
		//设置统一支付接口参数
		//设置必填参数
		//appid已填,商户无需重复填写
		//mch_id已填,商户无需重复填写
		//noncestr已填,商户无需重复填写
		//spbill_create_ip已填,商户无需重复填写
		//sign已填,商户无需重复填写
		$unifiedOrder->setParameter("openid",$openid);//商品描述
		$unifiedOrder->setParameter("body", $data['service_name']);//商品描述
		//自定义订单号，此处仅作举例
// 		$timeStamp = time();
// 		$out_trade_no = C('WxPayConf_pub.APPID').$timeStamp;

		$out_trade_no = $data ['order_number'];
		$unifiedOrder->setParameter("out_trade_no", $out_trade_no);//商户订单号
		$unifiedOrder->setParameter("total_fee", $pay*100);//总金额
		$unifiedOrder->setParameter("notify_url", 'http://t.meididi88.com/index.php/Pay/notify');//通知地址
		$unifiedOrder->setParameter("trade_type","JSAPI");//交易类型
		//非必填参数，商户可根据实际情况选填
		//$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商户号
		//$unifiedOrder->setParameter("device_info","XXXX");//设备号
		//$unifiedOrder->setParameter("attach","XXXX");//附加数据
		//$unifiedOrder->setParameter("time_start","XXXX");//交易起始时间
		//$unifiedOrder->setParameter("time_expire","XXXX");//交易结束时间
		//$unifiedOrder->setParameter("goods_tag","XXXX");//商品标记
		//$unifiedOrder->setParameter("openid","XXXX");//用户标识
		//$unifiedOrder->setParameter("product_id","XXXX");//商品ID
		 
		$prepay_id = $unifiedOrder->getPrepayId();
		//=========步骤3：使用jsapi调起支付============
		$jsApi->setPrepayId($prepay_id);
		 
		$jsApiParameters = $jsApi->getParameters();
		 
		$this->assign('orderId', $orderId);
		
		$this->assign('pay', $pay);
		$this->assign('user', getSessionUser());
		$this->assign('order', $data);
		$this->assign('beautician', $beauticianInfo);
		$this->assign('beauty', $BeautiParlorInfo);
		
		$this->assign('jsApiParameters',$jsApiParameters);
		$this->display('pay');
	}
	
	/**
	 * 生成订单号
	 * 
	 * @return string
	 */
	public function createOrder() {
		$order_number = '1'.substr(uniqid('', true), 15).substr(microtime(), 2, 8);
		$exits = M('order')->where(array('order_number' => $order_number))->find();
		if ($exits) {
			return $this->createOrder();
		} else {
			return $order_number;
		}
	}
	
    public function payStatus() {
    	$OrderNO = I ('get.orderNo');
    	
    	if (!$OrderNO) {
    		$this->ajaxReturn(array('status' => 0));
    	}
    	
    	$m = M('wx_shop_order');
    	$OrderInfo = $m->where(array('OrderNO'=> $OrderNO))->find();
    	if (!$OrderInfo) {
    		$this->ajaxReturn(array('status' => 0, 'info' => '查询订单信息不成功！'));
    	}
    	
    	$hasPay = $OrderInfo ['Status'] == 2 || $OrderInfo ['Status'] == 4;
    	$this->ajaxReturn(array('status' => 1, 'info' => '', 'data' => array('hasPay' => $hasPay)));
    }
    
    /**
     * 支付成功
     */
    public function paySuccess(){
    	$id = $_GET['id'];
    	
    	if (!isset($_GET['id'])) {
    		$this->error('参数有误！',U('ServiceItem/index'));
    		exit();
    	}
    	
    	$one = D('Order')->where(array('id'=>$id))->find();
    	if (empty($one)) {
    		$this->error('查询不到该订单！',U('ServiceItem/index'));
    		exit();
    	}
    	
//     	$ServiceItemModel = D('ServiceItem');
    	
//     	//美容师服务次数，完成服务后计算
//     	$BeautyModel->where(array('id' => $one ['beauty_id']))->setInc('service_total',1);
//     	$ServiceItemModel->where(array('id' => $one ['service_id']))->setInc('purchases_total',1);
    	
    	$this->ajaxReturn(array('status' => 1));
    }
    
//     public function sendMessage($openid) {
//     	$scriptName = $_SERVER ['SCRIPT_NAME'];
//     	$scriptName = substr($scriptName, 0,strlen($scriptName)-9);
    	 
//     	$jumpUrl = 'http://'.$this->_server('HTTP_HOST').$scriptName."index.php?s=/OldFriendsCard/index";
//     	$content = '你有1个订单（%s）服务，预约时间为%s，请安排好服务时间；';
    	 
//     	$txt = '{"touser":"'.$openid.'",
// 					    "msgtype":"text",
// 					    "text":
// 					    {
// 					         "content":"'.$content.'"
// 					    }
// 					}';
    	 
//     	$access_token = getAccessToken();
//     	$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token;
    	 
//     	$result = https_post($url,$txt);
//     }
     
//     public function testSendMessage() {
//     	$this->sendMessage('o9Iz4jh_N-wWRHPuv9G_ykG0X8x4');
//     }
    
    /**
     * 支付失败
     */
    public function payFail(){
    	$this->error('支付失败', U('/Order/userOrder'));
    }
    
     /**
     * 接口微信小店回传的交易通知，并改变对应的交易状态
     * 防止有人尝试猜回调的地址，所以这个回调地址要写特殊一点
     */
    public function notify(){
    	
    	//下面正式的
    	$xml = simplexml_load_string($GLOBALS['HTTP_RAW_POST_DATA'], 'SimpleXMLElement', LIBXML_NOCDATA);

    	$xml = (array) $xml;
    	$postStr = array_change_key_case($xml, CASE_LOWER);
    	$XMLSer = serialize($postStr);
    	
//     	$now = strftime("%Y-%m-%d-%H:%M:%S",time());
//     	paylogger('\n = '.$now.' = \n');
    	$ip = get_client_ip();
//     	paylogger('\n = notify client ip:'.$ip.' = \n');
//     	paylogger('\n = xmlser: '.$XMLSer.' = \n');
    	
    	try {
    		$mch_id = $postStr ['mch_id'];
    		$appid = $postStr ['appid'];
    	
    		$postStr['trade_mode'] = 1;
    		$postStr['trade_state'] = 0;
    		$postStr['partner'] = $mch_id;
    		$postStr['notify_id'] = 0;
    	} catch (Exception $e) {
    	}
    	 
//     	paylogger('\n # ser...set: '.serialize($postStr).' # \n');
    	 
    	$appSecretArr = getAppIdAndSecret();
    	
    	//因为签名按2.7版提供的数据验证不了，所以暂时只能做简单的验证，防止有人手动提交数据
    	if (!$appid || !$mch_id ||
	    	$appid != $appSecretArr['appId']) {
    		return '';
    	}
//     	paylogger('\n # ser...set: ********start notice********* # \n');
    	$data = array('sign_type'=>'MD5',
    			'input_charset'=>'UTF-8',
    			'sign'=>$postStr['sign'],
    			'trade_mode'=>$postStr['trade_mode'],
    			'trade_state'=>$postStr['trade_state'],
    			'partner'=>$mch_id,
    			'bank_billno'=>0,
    			'bank_type'=>$postStr['bank_type'],
    			'total_fee'=>$postStr['total_fee'],
    			'fee_type'=>$postStr['fee_type'],
    			'notify_id'=>$postStr['notify_id'],
    			'transaction_id'=>$postStr['transaction_id'],
    			'out_trade_no'=>$postStr['out_trade_no'],
    			'is_split'=>0,
    			'is_refund'=>0,
    			'attach'=>isset($attach)?$attach:0,
    			'time_end'=>$postStr['time_end'],
    			'transport_fee'=>0,
    			'product_fee'=>0,
    			'discount'=>0,
    			'rmb_total_fee'=>0,
    			'XML'=>$XMLSer);
    	 
    	$m = M('notice');
    	
    	$where = array('transaction_id'=>$data['transaction_id']);
    	$oldData = $m->where($where)->find();
    	$resultFlag = 0;
    	//因为微信服务器最多会返回8次，所以这里要判断数据库是否已经有相关数据
    	if (isset($oldData) && $oldData) {
    		$updateflag = $m->where($where)->save($data);
    		if(false !== $updateflag ){
    			//成功
    			$resultFlag = 1;
    		}else{
    			//失败
    			$resultFlag = 0;
    		}
    	}else {
    		$flag = $m->add($data);
    	
    		if ($flag) {
    			$resultFlag = 1;
    		}else{
    			$resultFlag = 0;
    		}
    	}
//     	paylogger('\n # ser...set: ********end notice********* # \n');
    	//插入通知成功
    	if ($resultFlag) {
//     		paylogger('\n # ser...set: ********update order********* # \n');
    		//更新订单状态
    		$orderNO = $data['out_trade_no'];
    		$where = array('order_number'=>$orderNO,'status'=>2);
    		$orderModel = D('Order');
    		$orderInfo = $orderModel->where($where)->find();
    	
    		if (!empty($orderInfo)) {
    			
    			$orderId = $orderInfo['id'];
    			$now = time();
    			$updateData = array('pay_date'=>$now,'status'=>1);
    			$updateOrderFlag = $orderModel->where(array('id'=>$orderId))->save($updateData);
    			$orderModel->clearCache($orderId);
    			
    			if ($orderInfo ['coupon_id']) {
    				$UserCouponModel = D('UserCoupon');
    				$UserCouponModel->where(array('id' => $orderInfo ['coupon_id']))->save(array('status' => 2, 'use_time' => time()));
//     				paylogger('\n # ser...set: coupon id use # \n');
    			}
    			
    			$setting = C('MESSAGE_TEMP');
    			$userMessageTemplate = $setting ['user_pay_success'];
    			$newOrderTemplate = $setting ['new_order'];
    			
    			$LchiObj = new LanzSMSDirectSendSMS();
    			$timeFormat = date('n月d日 H时', $orderInfo ['order_time']);
    			
    			$BeauticianModel = D('Beautician');
    			$BeautyModel = D('BeautyParlor');
    			$beauty = $BeautyModel->getBeautyInfo($orderInfo ['beauty_id']);
    			$beauticianInfo = $BeauticianModel->getBeauticianInfo($orderInfo ['beautician_id']);
    			
    			$content = sprintf($userMessageTemplate, $orderInfo ['service_name'],
    					$beauticianInfo['name'],
    					$beauticianInfo['mobile'],
    					$timeFormat,
    					$beauty['name'],
    					$orderInfo ['service_address']
    			);
    				
    			$orderUser = D('User')->getUserById($orderInfo ['user_id']);
    			$result = sendSMS($LchiObj, $orderUser ['mobile'], $content);
    			$params = array(
    					'mobile' => $orderUser ['mobile'],
    					'content' => $content,
    					'type' => 'pay_success',
    					'target_id' => $orderInfo ['user_id'],
    					'order_id' => $orderInfo ['id'],
    					'status' => $result?1:0
    			);
    			\Think\hook::listen('message_record', $params);
    				
    			$newOrderContent = sprintf($newOrderTemplate,
    					$beauticianInfo['name'],
    					$orderInfo ['service_name'],
    					$timeFormat,
    					$orderInfo ['service_address'],
    					$orderUser ['username'],
    					$orderUser ['mobile']
    			);
    			$result = sendSMS($LchiObj, $beauticianInfo ['mobile'], $newOrderContent);
    			$params = array(
    					'mobile' => $beauticianInfo ['mobile'],
    					'content' => $newOrderContent,
    					'type' => 'pay_success',
    					'target_id' => $orderInfo ['beautician_id'],
    					'order_id' => $orderInfo ['id'],
    					'status' => $result?1:0
    			);
    			\Think\hook::listen('message_record', $params);
    			 
    		} echo "success";
    	
    	}
    	
    }
}
    
